package org.dt.common.sequence.config;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.stream.Collectors;

import static org.apache.commons.lang3.StringUtils.isBlank;

/**
 * @author yujiadong
 * @create: 2019/02/27 16:27
 **/
public class ParseUtil {
    public static <T> T parseSpec( String spec,  T config) throws IllegalAccessException {
        if (isBlank(spec)) {
            return config;
        }

        Map<String, Field> fieldMap = FieldUtils.getAllFieldsList(config.getClass()).stream().collect(Collectors.toMap(Field::getName, x -> x));
        String[]           strings  = spec.split(",");
        for (String string : strings) {
            String[] split = string.split("=");
            Validate.notBlank(split[0], "key不能为空");
            Validate.notBlank(split[1], "value不能为空");
            Validate.isTrue(split.length == 2, "必须�?=分割");
            Validate.isTrue(fieldMap.containsKey(split[0]), String.format("%s 不是可接受的设置�? %s", split[0], fieldMap.keySet()));

            Field field = fieldMap.get(split[0]);
            FieldUtils.writeField(field, config, ConvertUtils.convert(split[1], field.getType()), true);
        }
        return config;
    }
}
